/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlCliente;
import Controlador.ControlProdServ;
import Controlador.ControlProveedor;
import Modelo.Cliente;
import Modelo.Proveedor;
import Modelo.Servicio;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Damian
 */
public class VisualizarClientes extends javax.swing.JFrame {

    /**
     * Creates new form VisualizarProveedores
     */
    ArrayList<Cliente> l;
    ControlCliente controlp = new ControlCliente();
    TableRowSorter<TableModel> rs;

    public VisualizarClientes() {
        initComponents();
        setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/Vista/Iconos/Publicont.png")));
        try {
            l = controlp.listar();
        } catch (SQLException ex) {

        }
        tabla.setModel(modelo());
        rs = new TableRowSorter<>(tabla.getModel());
        tabla.setRowSorter(rs);

        txtBuscar.getDocument().addDocumentListener(
                new DocumentListener() {
                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        filtrar();
                    }
                });
    }

    private void filtrar() {
        RowFilter<TableModel, Object> rf = null;
        try {
            rf = RowFilter.regexFilter(("(?i)") + txtBuscar.getText(), 1, 2, 3, 5);
        } catch (java.util.regex.PatternSyntaxException e) {
        }
        rs.setRowFilter(rf);
    }

    public DefaultTableModel modelo() {
        String[] columnas = {"Historia", "Empresa",
            "Nombres", "Apellidos", "RUC", "Ciudad",
            "Calle Principal", "Calle Secundaria", "Lote", "Teléfono"};
        DefaultTableModel tablaM = new DefaultTableModel(columnas, 0){

            @Override
            public boolean isCellEditable(int row, int column) {
                return false; //To change body of generated methods, choose Tools | Templates.
            }
            
        };
        try {
            l = controlp.listar();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        try {
            for (int i = 0; i < l.size(); i++) {
                Cliente p = l.get(i);
                tablaM.addRow(new Object[]{p.getHistoria(), p.getEmpresa(),
                    p.getNombres(), p.getApellidos(), p.getRuc(),
                    p.getCiudad(), p.getCalleprincipal(), p.getCallesecundaria(),
                    p.getNumerolote(), p.getTelefono()});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tablaM;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        btnAgregar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(100, 0), new java.awt.Dimension(100, 0), new java.awt.Dimension(100, 32767));
        jLabel1 = new javax.swing.JLabel();
        txtBuscar = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Clientes");

        jToolBar1.setRollover(true);

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-add.png"))); // NOI18N
        btnAgregar.setFocusable(false);
        btnAgregar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAgregar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnAgregar);

        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/view-form.png"))); // NOI18N
        btnModificar.setFocusable(false);
        btnModificar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnModificar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnModificar);
        jToolBar1.add(filler1);

        jLabel1.setText("Buscar:  ");
        jToolBar1.add(jLabel1);

        txtBuscar.setMaximumSize(new java.awt.Dimension(250, 2147483647));
        jToolBar1.add(txtBuscar);

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Código", "Empresa", "Teléfono", "Responsable", "Correo", "Ciudad", "Calle Principal", "Calle Secundaria", "Casa"
            }
        ));
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 809, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        RegistrarCliente ven = new RegistrarCliente();
        ven.setLocationRelativeTo(null);
        ven.setVisible(true);
        ven.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {
                actualizar();
            }

        });
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        
        DefaultTableModel model = ((DefaultTableModel) tabla.getModel());
        String[] columnas = {"Historia", "Empresa",
            "Nombres", "Apellidos", "RUC", "Ciudad",
            "Calle Principal", "Calle Secundaria", "Lote", "Teléfono"};
        int i = tabla.getSelectedRow();
        i = rs.convertRowIndexToModel(i);
        if (i >= 0) {
            Cliente p = new Cliente();
            p.setHistoria(Integer.parseInt(model.getValueAt(i, 0).toString()));
            p.setEmpresa(model.getValueAt(i, 1).toString());
            p.setNombres(model.getValueAt(i, 2).toString());
            p.setApellidos(model.getValueAt(i, 3).toString());
            p.setRuc(model.getValueAt(i, 4).toString());
            p.setCiudad(model.getValueAt(i, 5).toString());
            p.setCalleprincipal(model.getValueAt(i, 6).toString());
            p.setCallesecundaria(model.getValueAt(i, 7).toString());
            p.setNumerolote(model.getValueAt(i, 8).toString());
            p.setTelefono(model.getValueAt(i, 9).toString());
            
            ModificarCliente ven = new ModificarCliente(p);
            ven.setVisible(true);
            ven.addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosed(WindowEvent e) {
                    actualizar();
                }

            });

        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione un "
                    + "cliente de la tabla para modificar");
        }
    }//GEN-LAST:event_btnModificarActionPerformed

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        // TODO add your handling code here:
//        int i = tabla.getSelectedRow();
////                actualizar();
////                filtrar();
//        DefaultTableModel model = ((DefaultTableModel) tabla.getModel());
//        System.out.println("i: " + i + "cod: " + model.getValueAt(i, 0));
//        int c = rs.convertRowIndexToModel(i);
//        System.out.println("c: " + c + "cod: " + model.getValueAt(c, 0));
    }//GEN-LAST:event_tablaMouseClicked

    private void actualizar() {
        tabla.setRowSorter(null);
        rs = null;
        tabla.setModel(modelo());
        rs = new TableRowSorter<>(tabla.getModel());
        tabla.setRowSorter(rs);
        filtrar();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VisualizarClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VisualizarClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VisualizarClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VisualizarClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VisualizarClientes().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnModificar;
    private javax.swing.Box.Filler filler1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
